<script setup lang="jsx">
import { computed, reactive, ref } from 'vue';
import { useElementSize } from '@vueuse/core';
import { parseTime } from '@/utils';
import {
  downLoadPdfs,
  ppcontrolbatchAudit,
  ppcontrolbatchRevoke,
  ppcontroldelete,
  ppcontrolinbound,
  ppcontroloutbound,
  ppcontrolselect,
  ppcontrolupdate
} from '@/service/api/modules/erp';
import Modal from '@/components/common/modal.vue';
import Form from '@/components/common/form.vue';
import Search from './modules/search.vue';
const searchParams = ref({
  supplierName: '',
  state: '',
  auditingState: ''
});

const pagination = reactive({
  current: 1,
  pageSize: 200,
  showSizeChanger: true,
  pageSizeOptions: ['50', '100', '200', '300', '500', '1000'],
  showQuickJumper: true,
  showTotal: total => {
    return `共${total}条`;
  },
  total: 0,
  onChange: async (current, size) => {
    pagination.current = current;
    pagination.pageSize = size;
    getData();
  }
});
const upTit = ref(false);
const columns = ref([
  {
    key: 'index',
    dataIndex: 'index',
    title: '序号',
    width: 100,
    fixed: 'left',
    align: 'center',
    checked: true
  },
  {
    key: 'batchNumber',
    dataIndex: 'batchNumber',
    title: '生产批号',
    width: 230,
    fixed: 'left',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'failureState',
    dataIndex: 'failureState',
    title: '过期状态',
    width: 120,
    fixed: 'left',
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      if (record.failureState == 1) {
        return '正常';
      }
      if (record.failureState == 2) {
        return '即将过期';
      }
      if (record.failureState == 3) {
        return '已过期';
      }
      if (record.failureState == 4) {
        return '库存不足';
      }
    }
  },
  {
    key: 'auditingState',
    dataIndex: 'auditingState',
    title: '审核状态',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      if (record.auditingState == 1) {
        return '未审核';
      }
      if (record.auditingState == 2) {
        return '已审核';
      }
    }
  },
  {
    key: 'supplierName',
    dataIndex: 'supplierName',
    title: '供应商名称',
    width: 100,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'specif',
    dataIndex: 'specif',
    title: '物料规格',
    width: 240,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'inventory',
    dataIndex: 'inventory',
    title: '库存',
    width: 140,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'productionTime',
    dataIndex: 'productionTime',
    title: '生产时间',
    width: 200,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      if (record.productionTime == null) {
        return null;
      }
      return parseTime(record.productionTime);
    }
  },
  {
    key: 'expirationTime',
    dataIndex: 'expirationTime',
    title: '失效时间',
    width: 200,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      if (record.expirationTime == null) {
        return null;
      }
      return parseTime(record.expirationTime);
    }
  },

  {
    key: 'storageTime',
    dataIndex: 'storageTime',
    title: '入库时间',
    width: 200,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      if (record.storageTime == null) {
        return null;
      }
      return parseTime(record.storageTime);
    }
  },
  {
    key: 'createBy',
    dataIndex: 'createBy',
    title: '入库员',
    width: 140,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'outbound',
    dataIndex: 'outbound',
    title: '出库员',
    width: 140,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'changeTime',
    dataIndex: 'changeTime',
    title: '更改时间',
    width: 200,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      if (record.changeTime == null) {
        return null;
      }
      return parseTime(record.changeTime);
    }
  },
  {
    key: 'auditing',
    dataIndex: 'auditing',
    title: '审核人',
    width: 140,
    align: 'center',
    checked: true,
    ellipsis: true
  },

  {
    key: 'auditingTime',
    dataIndex: 'auditingTime',
    title: '审核时间',
    width: 200,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      if (record.auditingTime == null) {
        return null;
      }
      return parseTime(record.auditingTime);
    }
  }
]);
const formList = [
  {
    type: 'input',
    key: 'batchNumber',
    label: '生产批号',
    placeholder: '请输入生产批号',
    span: 8
  },
  {
    type: 'input',
    key: 'supplierName',

    label: '供应商名称',
    placeholder: '请输入供应商名称',
    span: 8
  },
  {
    type: 'input',
    key: 'specif',
    label: '物料规格',
    placeholder: '请输入物料规格',
    span: 8
  },
  {
    type: 'input',
    key: 'inventory',
    label: '库存',
    placeholder: '请输入库存',
    span: 8
  },
  {
    type: 'datePicker',
    key: 'productionTime',
    label: '生产时间',
    span: 8,
    showTime: true
  },
  {
    type: 'datePicker',
    key: 'expirationTime',
    label: '失效时间',
    span: 8,
    showTime: true
  },
  {
    type: 'datePicker',
    key: 'storageTime',
    label: '入库时间',
    span: 8,
    showTime: true
  },

  {
    type: 'input',
    key: 'createBy',
    label: '入库员',
    span: 8,
    showTime: true
  }
];
const formListqr = [
  {
    type: 'input',
    key: 'quantity',
    label: '数量',
    placeholder: '请输入数量',
    span: 24
  }
];
const tableData = ref([]);
const loading = ref(false);
const defaultExpandedRowKeys = ref([]);

function getData() {
  loading.value = true;
  ppcontrolselect({
    pageSize: pagination.pageSize,
    pageNum: pagination.current,
    ...searchParams.value
  })
    .then(({ data, error, otherData }) => {
      if (!error) {
        data.forEach((item, index) => {
          item.index = index + 1;
        });

        tableData.value = otherData.data;

        pagination.total = otherData.total;
      }
    })
    .finally(() => {
      loading.value = false;
    });
}
const selectedRowKeys = ref([]);

function tableSelectChange(val) {
  selectedRowKeys.value = val;
}

const detailsVisible = ref(false);
function getRowClassName(record) {
  // 检查每行的failureState是否为2，如果是，则返回一个类名，否则返回空字符串

  if (record.failureState == 2 || record.failureState == 3) {
    return 'jl-table-row-error';
  }
  return '';
}
const upDatas = ref('');

function updata(val) {
  if (selectedRowKeys.value.length != 1) {
    return window.$message?.error('请先选择一条数据');
  }
  upDatas.value = tableData.value.find(person => selectedRowKeys.value[0] == person.id);
  upTit.value = true;
  detailsVisible.value = true;
}
function closUpdata() {
  detailsVisible.value = false;
  upTit.value = false;
  selectedRowKeys.value = [];
}
function getUpdata() {
  ppcontrolupdate(upDatas.value).then(({ data, error }) => {
    if (!error) {
      detailsVisible.value = false;
      upDatas.value = '';
      window.$message?.success('修改成功');
      selectedRowKeys.value = [];
      upTit.value = false;
      getData();
    }
  });
}

function deleteData() {
  if (selectedRowKeys.value.length == 0) {
    return window.$message?.error('请先选择一条数据');
  }
  window.$modal?.confirm({
    title: `是否确认删除数据?`,

    onOk: () => {
      delRoyiUser(delIds).then(({ data, error }) => {
        if (!error) {
          const selectData = tableData.value.filter(item => selectedRowKeys.value.includes(item.id));

          ppcontroldelete(selectData).then(({ data, error }) => {
            if (!error) {
              selectedRowKeys.value = [];
              getData();
            }
          });

          window.$message?.success('删除成功');
        } else {
          window.$message?.error('删除失败!');
        }
      });
    },
    onCancel: () => {}
  });
}
const detailsVisibleQrcode = ref(false);
function openQrCode() {
  if (selectedRowKeys.value.length != 1) {
    return window.$message?.error('请先选择数据');
  }
  const qrData = tableData.value.find(person => selectedRowKeys.value[0] == person.id);
  const upDaras = {
    quantity: 1,
    category: 3,
    // materialSpec: qrData.specif.replace('%', ''),
    // barcodeText: qrData.id,
    // productionDate: qrData.productionTime
    codeInfo: qrData.barcode
  };
  downLoadPdfs(upDaras).then(({ data, error }) => {
    detailsVisibleQrcode.value = false;
    selectedRowKeys.value = [];
    const boldData = new Blob([data], { type: 'application/pdf' });
    const oldIframe = document.getElementById('printPdf');
    if (oldIframe) {
      oldIframe.parentNode.removeChild(oldIframe);
    }
    const iframe = document.createElement('iframe');
    iframe.style.frameborder = 'no';
    iframe.style.display = 'none';
    iframe.style.pageBreakBefore = 'always';
    iframe.setAttribute('id', 'printPdf');
    iframe.setAttribute('name', 'printPdf');
    iframe.src = window.URL.createObjectURL(boldData);
    document.body.appendChild(iframe);
    doPrint('printPdf');
    window.URL.revokeObjectURL(iframe.src);
  });
}

function doPrint(val) {
  const ordonnance = document.getElementById(val).contentWindow;
  setTimeout(() => {
    ordonnance.print();
  }, 500);
}
const boundTitle = ref('');
const crDatas = ref({});
function outbound() {
  if (selectedRowKeys.value.length == 0) {
    return window.$message?.error('请选择数据!');
  }
  boundTitle.value = '出库';
  detailsVisibleQrcode.value = true;
}
function inbound() {
  if (selectedRowKeys.value.length == 0) {
    return window.$message?.error('请选择数据!');
  }
  boundTitle.value = '入库';
  detailsVisibleQrcode.value = true;
}
function boundUpdata(val) {
  if (!crDatas.value.quantity) {
    return window.$message?.error('请输入数量!');
  }

  crDatas.value.id = selectedRowKeys.value[0];
  if (val == '出库') {
    ppcontroloutbound(crDatas.value).then(({ error, data }) => {
      if (!error) {
        window.$message?.success('出库成功!');
        crDatas.value = {};
        detailsVisibleQrcode.value = false;
        selectedRowKeys.value = '';
        boundTitle.value = '';
        getData();
      }
    });
  } else {
    ppcontrolinbound(crDatas.value).then(({ error, data }) => {
      if (!error) {
        window.$message?.success('入库成功!');
        crDatas.value = {};
        detailsVisibleQrcode.value = false;
        selectedRowKeys.value = '';
        boundTitle.value = '';
        getData();
      }
    });
  }
}
// ppcontrolbatchAudit
function checkData() {
  if (selectedRowKeys.value.length == 0) {
    return window.$message?.error('请先选择数据!');
  }
  window.$modal?.confirm({
    title: `是否确认审核数据?`,

    onOk: () => {
      delRoyiUser(delIds).then(({ data, error }) => {
        if (!error) {
          const selectData = tableData.value.filter(item => selectedRowKeys.value.includes(item.id));

          ppcontrolbatchAudit(selectData).then(({ data, error }) => {
            if (!error) {
              selectedRowKeys.value = [];
              getData();
            }
          });

          window.$message?.success('审核成功');
        } else {
          window.$message?.error('审核失败!');
        }
      });
    },
    onCancel: () => {}
  });
}
// ppcontrolbatchRevoke
function fallback() {
  if (selectedRowKeys.value.length == 0) {
    return window.$message?.error('请先选择数据!');
  }

  window.$modal?.confirm({
    title: `是否确认撤审数据?`,

    onOk: () => {
      delRoyiUser(delIds).then(({ data, error }) => {
        if (!error) {
          const selectData = tableData.value.filter(item => selectedRowKeys.value.includes(item.id));

          ppcontrolbatchRevoke(selectData).then(({ data, error }) => {
            if (!error) {
              selectedRowKeys.value = [];
              getData();
            }
          });

          window.$message?.success('撤审成功');
        } else {
          window.$message?.error('撤审失败!');
        }
      });
    },
    onCancel: () => {}
  });
}

const currentRowId = ref(null);
function onDblclick(record, index) {
  return {
    onDblclick: event => {
      upDatas.value = tableData.value.find(person => record.id == person.id);
      detailsVisible.value = true;
    },
    style: {
      background: record.id === currentRowId.value ? '#BAEAFA' : '',
      'background-color': [2, 3].includes(Number(record.failureState)) ? 'rgb(247, 109, 109)' : ''
    },
    class: `${record.id === currentRowId.value ? 'jl-table-row-selected' : ''}`,
    onClick() {
      currentRowId.value = record.id;
    }
  };
}
getData();

function search() {
  pagination.current = 1;

  getData();
}

const tableFooterRef = ref(null);
const { height } = useElementSize(tableFooterRef);

const footerHeight = computed(() => {
  return `${height.value + 20}px`;
});
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <Search v-model:model="searchParams" @reset="search()" @search="search()" />
    <ACard
      :bordered="false"
      :body-style="{ flex: 1, overflow: 'hidden' }"
      class="table-card flex-col-stretch sm:flex-1-hidden card-wrapper"
    >
      <template #title>
        <AButton type="primary" size="small" ghost class="mini-btn mr-8px" @click="updata('update')">
          <span class="ml-3px">修改</span>
        </AButton>
        <AButton type="primary" size="small" ghost class="mini-btn mr-8px" @click="deleteData">
          <span class="ml-3px">删除</span>
        </AButton>
        <AButton type="primary" size="small" ghost class="mini-btn mr-8px" @click="outbound">
          <span class="ml-3px">出库</span>
        </AButton>
        <AButton type="primary" size="small" ghost class="mini-btn mr-8px" @click="inbound">
          <span class="ml-3px">入库</span>
        </AButton>
        <AButton type="primary" size="small" ghost class="mini-btn mr-8px" @click="checkData">
          <span class="ml-3px">审核</span>
        </AButton>
        <AButton type="primary" size="small" ghost class="mini-btn mr-8px" @click="fallback">
          <span class="ml-3px">撤审</span>
        </AButton>
        <AButton type="primary" size="small" ghost class="mini-btn mr-8px" @click="openQrCode">
          <span class="ml-3px">二维码</span>
        </AButton>
      </template>
      <template #extra>
        <TableColumnSetting v-model:columns="columns" />
      </template>
      <STable
        :columns="columns"
        :data-source="tableData"
        size="small"
        bordered
        :loading="loading"
        :custom-row="onDblclick"
        :row-selection="{
          selectedRowKeys: selectedRowKeys,
          onChange: tableSelectChange
        }"
        :default-expanded-row-keys="defaultExpandedRowKeys"
        row-key="id"
        :default-expand-all-rows="true"
        :scroll="{ y: 'auto' }"
        :pagination="pagination"
        class="has-footer-table h-full"
        :row-height="23"
      >
        <template #footer>
          <div ref="tableFooterRef" style="display: flex; align-items: center">
            <div style="width: 20px; height: 14px; background-color: rgba(244, 56, 56, 0.7)"></div>
            <span>背景为三小时内过期</span>
          </div>
        </template>
      </STable>
    </ACard>

    <Modal
      v-model:visible="detailsVisible"
      :destroy-on-close="true"
      :centered="true"
      title="PP信息修改"
      width="1050px"
      height="550px"
    >
      <div class="event-form">
        <Form v-model:model="upDatas" :form-list="formList"></Form>
      </div>

      <template #footer>
        <div class="modal-footer">
          <AButton @click="closUpdata">关闭</AButton>
          <AButton v-if="upTit" @click="getUpdata">保存</AButton>
        </div>
      </template>
    </Modal>
    <Modal
      v-model:visible="detailsVisibleQrcode"
      :destroy-on-close="true"
      :centered="true"
      :title="boundTitle"
      width="550px"
      height="350px"
    >
      <div class="event-form">
        <Form v-model:model="crDatas" :form-list="formListqr"></Form>
      </div>

      <template #footer>
        <div class="modal-footer">
          <AButton @click="detailsVisibleQrcode = false">关闭</AButton>
          <AButton @click="boundUpdata(boundTitle)">保存</AButton>
        </div>
      </template>
    </Modal>
  </div>
</template>

<style lang="scss" scoped>
:deep(.surely-table-wrapper) {
  &.has-footer-table {
    .ant-spin-nested-loading {
      .ant-spin-container {
        .surely-table {
          height: calc(100% - 40px - v-bind('footerHeight')) !important;
        }
      }
    }
  }
}
</style>
